package com.ltmonitor.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Date;

import com.ltmonitor.entity.GPSRealData;
import com.ltmonitor.jt808.protocol.T808Message;
import com.ltmonitor.jt808.service.IT808Manager;
import com.ltmonitor.jt808.tool.Tools;
import com.ltmonitor.service.IRealDataService;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.util.DateUtil;
/**
 * 服务器程序命令行入口类
 * 如果是在linux上部署，就不能启动界面，只能在命令行启动整个程序
 * @author admin
 *
 */
public class MainService {

	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
			.getLogger(MainService.class);
	private static IT808Manager t808Manager;

	/**
	 * 不断的检测连接的最新上线时间
	 */
	private static Thread refreshOnlineDateThread;

	public static void main(String[] args) {

		String command = args[0];

		if ("start".equals(command)) {
			int listenPort = Integer.parseInt(args[1]);

			try {
				System.out.println("服务器开始加载配置并连接数据库...");
				ServiceLauncher.launch();
				boolean res = start(listenPort);
				if (res == false) {
					StopServer();
					return;
				}

				while (true) {
					String str = readDataFromConsole();
					if ("conn".equals(str)) {
					} else if ("quit".equals(str)) {
						StopServer();
						break;
					} else if ("stop".equals(str)) {
						StopServer();
						// break;
					} else if ("start".equals(str)) {
						res = start(listenPort);
						// break;
					} else if (str!=null && str.indexOf("log") == 0) {
						String[] param = str.split(",");
						if(param.length > 1 && "log".equals(param[0]))
						{
							GlobalConfig.filterSimNo = param[1];
							GlobalConfig.displayMsg = true;
						}
					}else if ("clear".equals(str)) {

						GlobalConfig.filterSimNo = null;
						GlobalConfig.displayMsg = false;
					}

					Thread.sleep(1000);
				}

			} catch (Exception ex) {
				logger.error("服务器启动错误:" + ex.getMessage(), ex);
			}
		}

	}

	private static IRealDataService realDataService;

	public static boolean start(int listenPort) {
		boolean res = false;
		try {
			realDataService = (IRealDataService) ServiceLauncher
					.getBean("realDataService");
			t808Manager = (IT808Manager) ServiceLauncher.getBean("t808Manager");
			t808Manager.setListenPort(listenPort);
			GlobalConfig.listenPort = (listenPort);
			res = t808Manager.StartServer();
			System.out.println("服务器监听端口:" + listenPort + ",启动"
					+ (res ? "成功" : "失败"));
			if (res) {
				refreshOnlineDateThread = new Thread(new Runnable() {
					public void run() {
						refreshOnlineDateThreadFunc();
					}
				});
				refreshOnlineDateThread.start();

			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return res;
	}

	private static void refreshOnlineDateThreadFunc() {
		long timerCount = 0;
		while (true) {
			refreshConnections();
			if (timerCount % 30 == 0)
				refreshConnections();
			else {

				T808Message tm = GlobalConfig.getMsgForDisplay();
				while (tm != null) {
					showMsg(tm);
					tm = GlobalConfig.getMsgForDisplay();
				}
			}

			timerCount++;
			if (timerCount > (Long.MAX_VALUE - 2))
				timerCount = 0;
			
			try {
				Thread.sleep(100L);
			} catch (InterruptedException e1) {
			}
		}
	}
	
	private static void showMsg(T808Message tm) {

		Date now = new Date();
		String strMsgType = "0x" + Tools.ToHexString(tm.getMessageType(), 2);
		String msgDescr = "[" + strMsgType + "]"
				+ JT808Constants.GetDescr(strMsgType);
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append(String.format(
				"消息类型：%1$s,Sim卡号：%2$s, 车牌号：%3$s,消息内容：%4$s,报文：%5$s,时间：%6$s",msgDescr, tm.getHeader().getSimId(),
						tm.getPlateNo(), tm.toString(), now.toLocaleString(),
						tm.getPacketDescr() ));
		logger.error(sBuilder.toString());
	}
	

	@SuppressWarnings("deprecation")
	private static void refreshConnections() {
		Collection<GpsConnection> connList = t808Manager.getGpsConnections();
		GlobalConfig.connectNum = connList.size();
		Date start = new Date();
		int connectNum = 0;
		for (GpsConnection conn : connList) {

			GPSRealData rd = realDataService.get(conn.getSimNo());
			if (rd != null) {
				conn.setPlateNo(rd.getPlateNo());
				//realDataService.updateOnlineTime(rd, conn.getOnlineDate());
			}
		}
		Date end = new Date();
		double seconds = DateUtil.getSeconds(start, end);
		///GlobalConfig.connectNum = connectNum;
		if (seconds > 3)
			logger.error("连接检索查询耗时:" + seconds + ",条数："
					+ GlobalConfig.connectNum);
		// GlobalConfig.totalLocationPacketNum = totalLocationPacketNum;
		// GlobalConfig.totalPacketNum = totalPacketNum;
		String staticText = "当前连接数:" + GlobalConfig.connectNum;
	}

	public static void StopServer() {
		t808Manager.StopServer();
		try {
			if (refreshOnlineDateThread != null)
				refreshOnlineDateThread.stop();
		} catch (Exception ex) {

		}
		logger.error("服务器已经终止");
	}

	private static String readDataFromConsole() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = null;
		try {
			// System.out.print(prompt);
			str = br.readLine();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

}
